from Tkinter import *
import math
import lattice

def drawLine(w,k1,k2,rscaling,offset,linewidth=0):
    k1c = lattice.convertToXYGrid(lattice.calcPolarCoords(k1),rscaling,offset)
    k2c = lattice.convertToXYGrid(lattice.calcPolarCoords(k2),rscaling,offset)

    if linewidth==0:
        w.create_line(k1c[0],k1c[1],k2c[0],k2c[1])
    else:
        w.create_line(k1c[0],k1c[1],k2c[0],k2c[1],width=linewidth)


def drawPopulation(popSize, popLabels, rmax, dim=200):
    master = Tk()
    w = Canvas(master, width=dim, height=dim)
    w.pack()

    offset = dim/2
    rscaling = dim/2 / rmax
    for k in popLabels:
        if 2*k in popLabels:
            drawLine(w,k,2*k,rscaling,offset, 5*popLabels[k]/popSize)
        if 2*k+1 in popLabels:
            drawLine(w,k,2*k+1,rscaling,offset, 5*popLabels[k]/popSize)
    #w.create_oval(1,1,dim,dim)
    mainloop()

def drawTree(labels,dim=200,rmax=0):
    master = Tk()
    w = Canvas(master, width=dim, height=dim)
    w.pack()

    if rmax == 0:
        rmax = math.floor(math.log(max(labels))/math.log(2))
    offset = dim/2
    rscaling = dim/2 / rmax
    for k in labels:
        if 2*k in labels:
            drawLine(w,k,2*k,rscaling,offset)
        if 2*k+1 in labels:
            drawLine(w,k,2*k+1,rscaling,offset)
    #w.create_oval(1,1,dim,dim)
    mainloop()



if __name__ == '__main__':
    gp = ['+', ['+',1,['-',3,5]], 4]
    import lattice
    drawTree(lattice.parseTreeToLattice(gp))
    pass

